<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible="showCreateClass"
      width="560px"
      append-to-body
      @close="cancel"
    >
      <div v-loading="formLoading">
        <div class="sign">
          注：排课后且有学生开始学习后，班级无法删除
        </div>
        <el-form
          :model="form"
          ref="teachingForm"
          size="small"
          :rules="rules"
          label-width="120px"
        >
          <el-form-item label="授课班级名称" prop="classTeachingName">
            <el-input
              maxlength="20"
              show-word-limit
              @blur="form.classTeachingName = form.classTeachingName.trim()"
              v-model="form.classTeachingName"
              placeholder="请输入授课班级名称"
              clearable
              style="width: 304px;"
            />
          </el-form-item>
          <el-form-item label="添加学生" prop="studentIdList">
            <el-cascader
              filterable
              collapse-tags
              style="width: 304px"
              v-model="form.studentIdList"
              placeholder="可搜索：分院/专业/班级/学生"
              :options="treeData"
              clearable
              multiple
              :props="{
                multiple: true,
                label: 'name',
                value: 'id',
                children: 'children',
                disabled: 'disabled'
              }"
            >
              <div slot="empty" class="search_empty">
                搜索学生已添加或不存在
              </div>
            </el-cascader>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button v-preventReClick @click="cancel">取 消</el-button>
        <el-button :loading="formLoading" v-preventReClick type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { convertStudentArrayWithCustomNames } from '@/views/teachIndex/formatOrganizationData'
import { addSchoolClassTeaching, editSchoolClassTeaching, getSchedulingStudentList, getSchoolClassTeachingInfo } from '@/api/teach/teach'

export default {
  name: 'classTeachingDialog',
  data() {
    return {
      treeData: [],
      formLoading: false,
      form: {
        classTeachingName: '',
        studentIdList: []
      },
      rules: {
        classTeachingName: [
          { required: true, message: '请输入授课班级名称', trigger: 'blur' }
        ],
        studentIdList: [
          { required: true, message: '请选择学生', trigger: 'change' }
        ]
      }
    }
  },
  props: {
    showCreateClass: {
      type: Boolean,
      default: false
    },
    classTeachingId: {
      type: [String, Number],
      default: ''
    },
    title: {
      type: String,
      default: '创建授课班级'
    }
  },
  watch: {
    showCreateClass: {
      handler(val) {
        if (val) {
          this.getStudentList()
          if (this.title == '编辑授课班级') {
            this.handleEdit()
          }
        }
      }
    }
  },
  methods: {
    async handleEdit() {
      this.formLoading = true
      try {
        let res = await getSchoolClassTeachingInfo(this.classTeachingId)
        const { code, data } = res
        if (code == 200) {
          this.form.classTeachingName = data.classTeachingName
          this.form.studentIdList = data.studentIdList
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.formLoading = false
      }
    },
    cancel() {
      this.resetForm('teachingForm')
      this.$emit('update:showCreateClass', false)
    },
    submitForm() {
      this.$refs.teachingForm.validate(async valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '正在添加中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          let studentIdList = this.form.studentIdList.map(subArray => subArray[subArray.length - 1])
          let params = {
            ...this.form,
            studentIdList: studentIdList
          }
          try {
            let res
            if (this.title == '创建授课班级') {
              res = await addSchoolClassTeaching(params)
            } else {
              params.classTeachingId = this.classTeachingId
              res = await editSchoolClassTeaching(params)
            }
            const { code } = res
            if (code == 200) {
              this.$modal.msgSuccess(`${this.title}成功`)
              this.cancel()
              this.$emit('refresh', true)
            }
          } catch (e) {
            console.error(e)
          } finally {
            loading.close()
          }
        } else {
          return false
        }
      })
    },
    async getStudentList() {
      try {
        let res = await getSchedulingStudentList()
        const { code, data } = res
        if (code == 200) {
          this.treeData = convertStudentArrayWithCustomNames(data)
        }
      } catch (e) {
        console.error(e)
      }
    }
  }
}
</script>

<style scoped lang="scss">
.sign {
  color: #FFB14C;
  margin-bottom: 5px;
}
</style>
